package cn.libinal.scloud.base.controller;

import cn.libinal.scloud.base.common.dto.DtoMapper;
import cn.libinal.scloud.base.common.dto.UserDto;
import cn.libinal.scloud.base.common.web.DataPageRequest;
import cn.libinal.scloud.base.common.web.ResultJson;
import cn.libinal.scloud.base.common.web.ResultPage;
import cn.libinal.scloud.base.entity.User;
import cn.libinal.scloud.base.service.UserService;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author libinal
 * created at 2018/11/4 20:37
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    private final UserService userService;
    private final DtoMapper dtoMapper;

    public UserController(UserService userService, DtoMapper dtoMapper) {
        this.userService = userService;
        this.dtoMapper = dtoMapper;
    }

    @PostMapping(name = "新增用户", path = "create")
    public ResultJson<User> create(User user) {
        return ResultJson.success(userService.create(user));
    }

    @PostMapping(name = "更新用户", path = "update")
    public ResultJson<User> update(User user) {
        return ResultJson.success(userService.update(user));
    }

    @PostMapping(name = "删除用户", path = "delete")
    public ResultJson<String> delete(String id) {
        userService.delete(id);
        return ResultJson.success("删除用户成功");
    }

    @GetMapping(name = "分页查询用户列表", path = "findByPaging")
    public ResultPage<User> findByPaging(@QuerydslPredicate(root = User.class, bindings = UserService.class) Predicate predicate, DataPageRequest pageRequest) {
        return ResultPage.buildPage(userService.findByPaging(predicate, pageRequest));
    }

    @PostMapping(name = "关联角色", path = "relateRoles")
    public ResultJson<String> relateRoles(String userId, @RequestBody List<String> roleIds) {
        userService.relateRoles(userId, roleIds);
        return ResultJson.success("角色分配成功");
    }

    @GetMapping(name = "根据用户名查询用户", path = "findByUsername")
    public ResultJson<UserDto> findByUsername(@RequestParam("username") String username) {
        User user = userService.findByUsername(username);
        UserDto userDto = dtoMapper.map(user, UserDto.class);
        log.info("User: {}", userDto);
        return ResultJson.success(userDto);
    }
}
